package p.ithorns.integration.sharding;

import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.shardingjdbc.jdbc.core.datasource.ShardingDataSource;
import org.apache.shardingsphere.underlying.common.exception.ShardingSphereException;
import org.apache.shardingsphere.underlying.common.rule.DataNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

/**
 * TableCreator
 *
 * @author ithorns
 * @version 1.0
 * @date 2021/9/6 23:43
 */
@Slf4j
@Component
public class TableCreator {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private TableNamesConfig tableNamesConfig;

    /**
     * 动态更新 处理化的表配置
     *
     * @param data 表名称
     */
    public void actualTablesRefresh(Integer data) {
        try {
            System.out.println("---------------------------------");
            ShardingDataSource shardingDataSource = (ShardingDataSource) this.dataSource;
            if (tableNamesConfig.getNames() == null || tableNamesConfig.getNames().length == 0) {
                log.info("dynamic.table.names为空");
                return;
            }
            for (int i = 0; i < tableNamesConfig.getNames().length; i++) {
                TableRule tableRule = null;
                try {
                    tableRule = shardingDataSource.getRuntimeContext().getRule().getTableRule(tableNamesConfig.getNames()[i]);
                } catch (ShardingSphereException e) {
                    log.error("报错啦" + e.getMessage());

                }
                assert tableRule != null;
                List<DataNode> dataNodes = tableRule.getActualDataNodes();
                Field actualDataNodesField = TableRule.class.getDeclaredField("actualDataNodes");
                Field modifiersField = Field.class.getDeclaredField("modifiers");
                modifiersField.setAccessible(true);
                modifiersField.setInt(actualDataNodesField, actualDataNodesField.getModifiers() & ~Modifier.FINAL);
                actualDataNodesField.setAccessible(true);
                List<DataNode> newDataNodes = new ArrayList<>();
                int time = tableNamesConfig.getStartYear();
                String dataSourceName = dataNodes.get(0).getDataSourceName();
                while (true) {
                    DataNode dataNode = new DataNode(dataSourceName + "." + tableNamesConfig.getNames()[i] + "_" + time);
                    newDataNodes.add(dataNode);
                    time = time + 1;
                    if (time > data.intValue()) {
                        break;
                    }
                }
                actualDataNodesField.set(tableRule, newDataNodes);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("初始化 动态表单失败" + e.getMessage());
        }
    }

}
